var currentUserPwd = "";
/*
 * 此处不考虑跨浏览器
 * 一律视为IE
 * @author wanyi@35.cn(WinyWan) 2008-05-21
 */
function Login()
{
	var formEle = document.getElementById("loginFormId");
	
	if ($("#userName").attr("value").trim()=='')
	{
		confirmDialog({content:"请输入用户名！",closeCallback:function(){jQuery('#userName').focus();}});
		return false;
	}
	if($("#userName").attr("value").indexOf("@")==-1)
	{
		confirmDialog({content:"用户名不合法，请重新输入！",closeCallback:function(){jQuery('#userName').focus();}});
		return false;
	}
	
	CoookieUtils.set("userName",formEle.userName.value);
	if ($("#userPwd").attr("value").trim()=='')
	{
		confirmDialog({content:"请输入密码！",closeCallback:function(){jQuery('#userPwd').focus();}});
		return false;
	}
	
	if (formEle.validateCode && formEle.validateCode.value.trim()=='')
	{
		confirmDialog({content:"请输入验证码！",closeCallback:function(){jQuery('#validateCode').focus();}});
		return false;
	}		
	$("#loginMsg").attr("oldInnerHTML",$("#loginMsg").prop("innerHTML"));
	$("#loginMsg").prop("innerHTML", "正在登录,请稍候...");
	currentUserPwd = $("#userPwd").attr("value");
	if (!checkUsbKey()){
		resetUI();
		return;
	}
	
	
	if (formEle.chkSSL && formEle.chkSSL.checked)		//是否SSL登录
	{
		formEle.submit();
	}
	else
	{
		var params = serilizeTxt(formEle);
		if(params)
		{
			var curDate = new Date(); 
			params += "&timsStamp=" + curDate.getTime();
		}
		$.post("member_login.do",params,resultHandler);
	}
	
	setUIDisabled(formEle);
}
function setUIDisabled(formEle){
	formEle.userName.disabled = true;
	formEle.userPwd.disabled = true;
	formEle.btnLogin.disabled = true;
	if(formEle.chkSSL)formEle.chkSSL.disabled=true;
	formEle.btnLogin.className="login-btn-dis";
	if (formEle.validateCode)
		formEle.validateCode.disabled = true;
}
function resetUI()
{
	$("#userName").prop("disabled", false);
	$("#userPwd").prop("disabled", false);
	$("#userPwd").prop("value", "");
	$("#btnLogin").prop("disabled", false);
	if($("#chkSSL"))$("#chkSSL").prop("disabled",false);
	$("#btnLogin").removeClass().addClass("login-btn");
	if ($("#validateCode").length>0)
	{
		$("#validateCode").prop("disabled", false);
		$("#validateCode").prop("value", "");
	}
	$("#loginMsg").prop("innerHTML", $("#loginMsg").attr("oldInnerHTML"));	
}

function checkUsbKey()
{
	if (isNeedUsbKey()==1)
	{
		var r = Milan.UsbKey.readLoginInfoFromUsbKey({
			notifyBrowerError:false,
			notifyInitOCXError:false
		});			
		if (!r)
		{
			confirmDialog({content:"读取USBKey时发生未知错误！"});
			return false;
		}		
		if (r==-3) 
		{
			confirmDialog({content:"登录当前账号需要使用USBKey功能，目前只支持IE浏览器。"})
			return false;;
		}		
		if (r==-1)
		{
			confirmDialog({content:"无法初始化USBKey登录控件，请确认浏览器或安全软件是否禁用了USBKey登录控件！"})
			return false;
		}		
		if (r==-2)
		{
			confirmDialog({content:"系统无法读取USBKey中的信息，请确定已<a href='/desktop/HaiKeyCSP驱动.zip' style='color:red'>安装驱动</a>，或确认已插入USBKey，或重新插拔后再试！",
				reloginBtn:true,
				reloginBtnFun:function(){
					$("#userPwd").val(currentUserPwd);
					Login();
				}
			});
			return false;
		}
		$("#usbKeyUserInfo").attr("value",r.userName);
		$("#usbKeyId").attr("value",r.keyId);
		return true;
	}
	return true;
}

function isNeedUsbKey()
{
	/*
	var userName = $("#userName").attr("value");
	var userDomain = $("#userDomain").attr("value");
	var result;
	var curDate = new Date(); 
	$.ajax(
		{
			async:false,
			url:"member_index.do",
			data:"timsStamp=" + curDate.getTime()+"&userName="+userName+(userDomain?"&userDomain="+userDomain:""),
			dataType:"text",
			success:function(data, textStatus){
				result = data;
			}
		}
	);
	return result;*/
	return 0;
}

function resultHandler(responseXML)
{
	var result = responseXML.getElementsByTagName("result")[0].firstChild.nodeValue;
	var message = responseXML.getElementsByTagName("error-message")[0].firstChild.nodeValue;
	var errorType = responseXML.getElementsByTagName("error-type")[0].firstChild.nodeValue;
	if(!eval(result)&&(errorType!=2))
	{
		confirmDialog({content:message,closeCallback:function(){window.location.reload();}});
	}
	else
	{
		var curDate = new Date(); 
		location.replace("index.do?timsStamp=" + curDate.getTime());
	}
}

function serilizeTxt(formObj)
{
   var formElements = formObj.elements;

   var hashmap = "";
   for(var i=0,ilen=formElements.length;i<ilen;i++)
   {
	  if(formElements[i].type=="text"||formElements[i].type=="password"||formElements[i].type=="hidden")
	  {
		  hashmap += "&" + formElements[i].name + "=" + encodeURIComponent(formElements[i].value);
	  }
   }
   return hashmap.substr(1,hashmap.length);
}

CoookieUtils = {};
CoookieUtils.set = function(key,value)
{
	document.cookie = key + "=" +value + ";expires = Fri, 31 Dec 2999 23:59:59 GMT";
}

CoookieUtils.get = function(key)
{
	var cookies = document.cookie;
	if((!cookies)||cookies.length<1) return null;
	var pairs = cookies.split(";");
	var cookie;
	for(var i=0,ilen=pairs.length;i<ilen;i++)
	{
		cookie = pairs[i].split("=");
		if(cookie&&cookie[0].trim()==key)
			return cookie[1];
	}
}

CoookieUtils.clear = function(key)
{
	document.cookie = key + "=null;expires=Fri, 31 Dec 1999 23:59:59 GMT";
}

function refreshValidateCode()
{
	var curDate = new Date();
	var validateImg = document.getElementById("validateCodeImg");
	validateImg.src = "startpageAction.do?actionType=14" + "&timestamp=" + curDate.getTime();
}

String.prototype.trim  =  function()
{
	return  this.replace(/(^\s*)|(\s*$)/g,  "");
}

function handleKeyDown(e)
{
	if(jQuery("#confirmDialog_divId").length >0){//如果存在提示框则不触发login事件
		return;
	}
	var evt = window.event || e;
	if (!evt) confirmDialog({content:"浏览器不支持!"});
	if((evt.keyCode || evt.which) == 13)
	{
		var index_LoginFormEle = document.getElementById("loginFormId");
		var userName = index_LoginFormEle.userName;
		var userPwd = index_LoginFormEle.userPwd;
		var validateCode = index_LoginFormEle.validateCode;
		if(userName.value.trim().length<1)
		{
			confirmDialog({content:"用户名不能为空!",closeCallback:function(){$('#userName').focus();}});
			return;
		}
		if(userPwd.value.trim().length<1)
		{
			confirmDialog({content:"用户密码不能为空!",closeCallback:function(){$('#userPwd').focus();}});
			return;
		}
		if(validateCode&&validateCode.value.trim().length<1)
		{
			confirmDialog({content:"验证码不能为空!",closeCallback:function(){$('#validateCode').focus();}});
			return;
		}
		Login();
	}
}
function changeCHKSSL(obj){
	CoookieUtils.set("ssl",obj.checked?"y":"n");
}
var windowOnload = function()
{
	try
	{
		var formEle = document.getElementById("loginFormId");
	    var userName = CoookieUtils.get("userName");
		if(userName) formEle.userName.value = userName;
		//reset input's disabled attribute,for FF
		formEle.userName.disabled = false;
		formEle.userPwd.disabled = false;
		formEle.btnLogin.disabled = false;
		if(formEle.chkSSL){
			var chkSSL1 = CoookieUtils.get("ssl");
			if(chkSSL1 =="n")
				formEle.chkSSL.checked = false;
			formEle.chkSSL.disabled=false;
		}
		formEle.btnLogin.className="login-btn";
		if (formEle.validateCode)
			formEle.validateCode.disabled = false;
		if (formEle.userName.value.trim()=="")
			formEle.userName.focus();
		else
			formEle.userPwd.focus();
	}
	catch(err)
	{
	}
	/*var errMsg = document.getElementById("errmsg_input").value;
	if (errMsg && !errMsg.trim().equals("")) 
	{
		alert(errMsg);
	}*/
}
if (document.addEventListener){
	document.addEventListener("keydown",handleKeyDown,false);
}else{
	if (document.attachEvent){
		document.attachEvent("onkeydown", handleKeyDown);
	}
}
windowOnload();
function confirmDialog(config){
	var _config = {};
	var ensureDefault = function (prop, defaultValue) {
		var setting = config[prop];
		if (setting != undefined) {
			_config[prop] = setting;
		} else {
			_config[prop] = defaultValue;
		}
	};
	ensureDefault("content",'');
	ensureDefault("closeCallback",null);
	ensureDefault('title',"提示信息");
	ensureDefault("width",300);
	ensureDefault("reloginBtn",false);
	ensureDefault("reloginBtnFun",null);
	var top = (document.body.scrollTop + ((document.body.clientHeight - 150)/2))+"px";
	var left = (screen.availWidth - _config.width)/2 + "px";
	jQuery("#confirmDialog_divId").remove();
	jQuery("#loadingDiv").remove();
	var html = '<div id="loadingDiv" class="masker"><iframe class="iframe-masker"></iframe></div><div id="confirmDialog_divId" class="popup popup_width" style="width:' + _config.width+
			'px; z-index: 103; visibility: visible; top: ' +top+
			'; left: ' + left +
			'"><div class="popup_top_left"><div class="popup_top_right"><div class="pop_close">' +
			'<a class="pop_hint_close" href="javascript:void(0)" title="关闭" id="closeConfirmDialog_btn1"></a></div><h2>' +
			_config.title + '</h2></div></div><div class="popup_main_left"><div class="popup_main_right">' +
			'<div class="popup_main_content"><div style="text-align:center">' + _config.content + 
			'</div></div><div class="win-btn-panel">' ;
			if(_config.reloginBtn){
				html = html + '<a class="btn_short" id="relogin_btn1">重 试</a>&nbsp;&nbsp;<a class="btn_short" id="closeConfirmDialog_btn2">取 消</a>';
			}else{
				html = html + '<a class="btn_short" id="closeConfirmDialog_btn2">确 认</a>';
			}
			html = html + '</div></div></div><div class="popup_btm_left"><div class="popup_btm_right"></div></div></div>';
	jQuery('body').append(html);
	setUIDisabled(document.getElementById("loginFormId"));
	jQuery("a[id^=closeConfirmDialog_btn]").click(function(){closeConfirmDialog(_config.closeCallback);});
	if(_config.reloginBtnFun){
		jQuery("a[id=relogin_btn1]").click(function(){closeConfirmDialog();_config.reloginBtnFun();});
	}
}
function closeConfirmDialog (callback){
	jQuery("#confirmDialog_divId").remove();
	jQuery("#loadingDiv").remove();
	jQuery("#userName").prop("disabled", false);
	jQuery("#userPwd").prop("disabled", false);
	jQuery("#btnLogin").prop("disabled", false);
	jQuery("#btnLogin").removeClass().addClass("login-btn");
	if($("#chkSSL"))$("#chkSSL").prop("disabled",false);
	if (jQuery("#validateCode").length>0)
	{
		jQuery("#validateCode").prop("disabled", false);
		jQuery("#validateCode").prop("value", "");
	}
	jQuery("#loginMsg").prop("innerHTML", jQuery("#loginMsg").prop("oldInnerHTML"));	
	if(callback){
		callback();
	}
}